/*jslint vars: true, forin: true, sloppy: true */
/*global angular, ocDialog, DialogManager, DialogFactory */
ocDialog.directive("ocDataList", function () {
	return {
		restrict: 'E',
		replace: true,
		scope: {
			setup: '='
		},
		template:
			'<div class="oc-data-list" ng-click="clearSelect()"><header><label ng-repeat="l in field track by $index"' +
				'ng-style="{width:l.width||\'125px\'}"><hr/>{{l.title}}</label></header>' +
				'<section><table><thead><tr><th ng-repeat="l in field track by $index">' +
					'<div ng-style="{width:l.width||\'125px\'}">&nbsp;</div></th></tr></thead>' +

					'<tbody><tr ng-click="select($index, $event)" ' +
						'ng-class="{active:setup.selected==$index}" ' +
						'ng-repeat="r in data track by $index">' +
						'<td ng-repeat="l in field track by $index">' +
							'<span>{{r[l.key]}}</span></td>' +
				'</tbody></table></section></div>',
		link: function (scope, element, attrs) {
			scope.data = scope.setup.data;
			scope.field = scope.setup.field;

			// A function call when a item was selected by click.
			scope.select = function (index, event) {
				event.stopPropagation();

				if (scope.setup.selected === index) {
					(scope.setup.visitFn || angular.noop).call(scope.data, index, event);
				} else {
					scope.setup.selected = index;
					(scope.setup.selectFn || angular.noop).call(scope.data, index, event);
				}
			};

			scope.clearSelect = function () {
				scope.setup.selected = -1;
			};
		}
	};
});
